package com.mergeades.chp02;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 静态方法加锁测试
 */
public class SyncronizedStaticClassTest {

    public static void main(String[] args) {

        Thread t1 = new Thread(() -> {
            SyncronizedStaticClass.change();
        });
        Thread t2 = new Thread(() -> {
            SyncronizedStaticClass.change();
        });
        ExecutorService es = Executors.newCachedThreadPool();
        es.execute(t1);
        es.execute(t2);
        es.shutdown();
    }
}


class SyncronizedStaticClass {

    private static int num = 200;

    public synchronized static void change() {
        for (int i = 0; i < 10; i++) {
            try {
                num--;
                System.out.println(Thread.currentThread().getName() + ",num=" + num);
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

}